/*
 * QTXpost - a Qt-based blog client.
 * Copyright (C) 2010 Helen Sommer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (in COPYING); if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA  02111-1307  USA
 *
 * The project is hosted on http://code.google.com/p/qtxpost
 */

#include "EditGroup.h"
#include "MainWindow.h"

extern MainWindow *root;

EditGroup::EditGroup(QWidget *parent) 
  : QDialog(parent)
{
  setupUi(this);

  connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
  connect(updateButton, SIGNAL(clicked()), this, SLOT(updateGroup()));
  connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteGroup()));
}

void EditGroup::switchMode(int mode)
{
  if (mode == MODE_TRUSTGROUPS) {
    sortOrderSpin->setMaximum(255);
  }
  else {
    sortOrderSpin->setMaximum(65535);
  }
}

void EditGroup::initialize(GroupTreeWidgetItem *item_)
{
  QSqlQuery query;
  QString command;

  item = item_;
  nameLine->setText(item->name);

  int type = (root->friendsManager->currentTab == MODE_TRUSTGROUPS) ? 0 : 1;

  command = QString("select public, sortorder from groups where users_id=%1 and bit=\"%2\" and type=%3").arg(root->friendsManager->server->id).arg(item->id).arg(type);
  query.exec(command);
  if (query.size() == 0) return; // shouldn't happen
  query.next();
  bool isPublic = query.value(0).toInt();
  int sortOrder = query.value(1).toInt();
  publicToggle->setChecked(isPublic);
  sortOrderSpin->setValue(sortOrder);
  show();

}

void EditGroup::updateGroup()
{
  int isPublic = (publicToggle->isChecked()) ? 1 : 0;
  item->setText(0, nameLine->text().simplified());
  root->friendsManager->updateGroupStart(item, isPublic, sortOrderSpin->value());
  close();
}

void EditGroup::deleteGroup()
{
  QMessageBox msgBox(this);
  QString message = QString(tr("Really delete group %1?")).arg(item->name);
  msgBox.setText(message);
  msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  msgBox.setDefaultButton(QMessageBox::No);
  if (msgBox.exec() == QMessageBox::Yes) {
    root->friendsManager->deleteGroupStart(item);
  }
  close();
}
